package org.cogaen.java2d;

import java.awt.Color;
import java.awt.Font;

import org.cogaen.core.Core;
import org.cogaen.logging.LoggingService;
import org.cogaen.resource.ResourceHandle;
import org.cogaen.resource.ResourceManager;

public class TextHandle extends ResourceHandle {

	private static final String LOGGING_SOURCE = ResourceManager.LOGGING_SOURCE;
	private TextVisual textVisual;
	private String fontName;
	private String colorName;
	private String text;
	private double offsetX;
	private double offsetY;

	public TextHandle(String resourceName, String text, String fontName, String colorName, double offsetX, double offsetY) {
		super(resourceName);
		this.text = text;
		this.fontName = fontName;
		this.colorName = colorName;
		this.offsetX = offsetX;
		this.offsetY = offsetY;
	}
	
	public TextHandle(String resourceName, String text, String fontName, String colorName) {
		this(resourceName, text, fontName, colorName, 0, 0);
	}
	
	public TextHandle(String name, String text) {
		this(name, text, null, null);
	}

	@Override
	public boolean isLoaded() {
		return this.textVisual != null;
	}

	@Override
	public void load(Core core) {

		if (this.text != null) {
			this.textVisual = new TextVisual(this.text);
		} else {
			this.textVisual = new TextVisual();
		}
		
		if (this.fontName != null) {
			ResourceManager resMngr = ResourceManager.getInstance(core);
			if (resMngr.hasResource(this.fontName)) {
				this.textVisual.setFont((Font) resMngr.getResource(this.fontName));
			} else {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "referenced font '" + this.fontName + "' not found");
			}
		}
		
		if (this.colorName != null) {
			ResourceManager resMngr = ResourceManager.getInstance(core);
			if (resMngr.hasResource(this.colorName)) {
				this.textVisual.setColor((Color) resMngr.getResource(this.colorName));
			} else {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "referenced font '" + this.colorName + "' not found");
			}			
		}
		
		this.textVisual.setOffset(this.offsetX, this.offsetY);
	}

	@Override
	public void unload() {
		this.textVisual = null;
	}

	@Override
	public Object getResource() {
		return this.textVisual;
	}
	
}
